package com.rongchuang.controller;

import com.rongchuang.dto.RoleDTO;
import com.rongchuang.dto.UserDTO;
import com.rongchuang.service.RoleService;
import com.rongchuang.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserService userService;

    /**
     * 分页查询角色信息
     */
    @GetMapping("page")
    public Page<RoleDTO> pageSearch(@RequestParam(defaultValue = "0") int pageNum,
                                    @RequestParam(defaultValue = "10") int pageSize,
                                    String name) {
        return roleService.pageSearch(pageNum, pageSize, name);
    }

    /**
     * 保存角色信息
     */
    @PostMapping("modify")
    public void modify(HttpServletRequest request,
                       @RequestBody RoleDTO roleDTO) {
        Long associationId = getAssociationIdByUserId(request);
        // 所属商会
        roleDTO.setAssociationId(associationId);
        roleService.modify(roleDTO);
    }

    /**
     * 获取角色信息
     */
    @GetMapping("detail/{id}")
    public RoleDTO detail(@PathVariable Long id) {
        return roleService.getDetail(id);
    }

    /**
     * 获取角色列表
     * @return 角色列表
     */
    @GetMapping("list")
    public List<RoleDTO> list(HttpServletRequest request) {
        Long associationId = getAssociationIdByUserId(request);
        return roleService.findByAssociationId(associationId);
    }

    /**
     * 根据用户id获取所属商会id
     */
    private Long getAssociationIdByUserId(HttpServletRequest request) {
        // 获取用户id
        Long userId = (Long)request.getAttribute("userId");
        UserDTO userDTO = userService.getDetail(userId);
        return userDTO.getAssociationId();
    }
}
